package com.hzw.saas.web.storage.security;

import com.hzw.saas.api.user.IUserAccountService;
import com.hzw.saas.api.user.bo.UserAccountBO;
import com.hzw.saas.api.user.query.UserAccountGetQuery;
import com.hzw.saas.common.security.enums.UserType;
import com.hzw.saas.common.security.pojo.dto.SaasUser;
import com.hzw.saas.common.util.AccountValidatorUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.Collection;

/**
 * 需要登录这里才需要实现，否则不实现
 * 用户信息服务
 * TODO 这里应该调用用户中心的查询接口
 * @author zzl
 * @since 12/21/2020
 */
@Slf4j
@Component
@AllArgsConstructor
public class UserDetailsServiceImpl implements UserDetailsService {

    private final IUserAccountService userAccountService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserAccountBO userAccount = null;
        // 验证用户名
        if (userAccount == null) {
            userAccount = userAccountService.getAccount(new UserAccountGetQuery().setUserName(username));
        }
        // 验证邮箱
        if (AccountValidatorUtil.isEmail(username)) {
            userAccount = userAccountService.getAccount(new UserAccountGetQuery().setEmail(username));
        }
        // 验证手机号
        if (userAccount == null && AccountValidatorUtil.isMobile(username)) {
            userAccount = userAccountService.getAccount(new UserAccountGetQuery().setPhoneNo(username));
        }
        //
        if (userAccount == null) {
            throw new UsernameNotFoundException("用户名或密码错误");
        }
        //
        Collection<? extends GrantedAuthority> authorities
            = AuthorityUtils.createAuthorityList(getUserPermissions(userAccount.getUserId()));

        return new SaasUser(userAccount.getUserId(), userAccount.getUserName(), userAccount.getPhoneNo(),
            userAccount.getEmail(), UserType.SAAS_USER.code()
            , userAccount.getPassword(), userAccount.getStatus() == 1, authorities);
    }

    private String[] getUserPermissions(String userId) {
        return new String[]{};
    }
}
